#include "led_screen.h"

int lite_led_display_debug(char *type, char *fun, char *param);
xp_bool led_screen_init()
{
    int ret = -1;
    ret = xp_modbus_init(2, 9600, MB_PAR_NONE, 100);
    if(0 != ret){
        perr("led_screen_init fail! ret %d", ret);
        return false;
    }
    xp_cli_debug_add(lite_led_display_debug);
    return xp_true;
}

int led_screen_write_register(uint8_t port, uint8_t id, uint16_t addr, uint16_t *data, uint8_t len)
{
    int sta = 0;
    uint8_t rec_data[20] = {0};
    uint8_t rec_len = 0;
    MB_data modbus;
    uint8_t try_times = 3;

    modbus.slave_id = id;
    modbus.mb_fun = mb_single_w;
    modbus.start_addr = addr;
    modbus.wBuf = data;
    modbus.rwLen = len;
    modbus.resBuf = rec_data;
    modbus.resLen = &rec_len;
    while(try_times--){
        if( 0 == xp_modbus_ask(port, &modbus) ) return 0;
    }

    return -1;
}

/**
 * @brief LED显示屏设置显示节目
 * 
 * @param led_screen modbus设备对象
 * @param item  节目编号
 * @return xp_bool 设置成功返回xp_true,否则返回xp_false
 */
xp_bool led_screen_item_display(led_display_item_t item)
{
    unsigned short addr = 0x0FA0;
    unsigned short data = item;
    int ret = led_screen_write_register(2, 2, addr, &data, 2);

    return (ret != 0) ? xp_false : xp_true;
}

int lite_led_display_debug(char *type, char *fun, char *param)
{
    if (strcmp(type, "led_display") != 0) return 0;
    led_screen_item_display(atoi(fun));
    return 1;
}
